package cn.edu.sdjzu.xg.eagle.xg23_kcsj_01.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/file")
public class FileController {
    @PostMapping("/upload")
// 修改参数名为files，并接收数组
    public ResponseEntity<?> uploadFile(@RequestParam("files") MultipartFile[] files) {
        System.out.println("开始文件上传");
        try {
            List<String> fileUrls = new ArrayList<>();
            String uploadDir = "E:/wenjian/temp/";

            for (MultipartFile file : files) {
                // 创建临时目录（如果不存在）
                File tempDir = new File(uploadDir);
                if (!tempDir.exists()) {
                    tempDir.mkdirs();
                }

                // 生成唯一文件名
                String originalFilename = file.getOriginalFilename();
                String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                String fileName = UUID.randomUUID() + fileSuffix;

                // 保存文件
                file.transferTo(new File(uploadDir + fileName));
                fileUrls.add("wenjian/temp/" + fileName);
            }

            return ResponseEntity.ok(Map.of(
                    "code", 200,
                    "data", fileUrls
            ));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of(
                    "code", 500,
                    "message", "文件上传失败: " + e.getMessage()
            ));
        }
    }
}
